package service

import (
	"fmt"
	"hanyun-admin/src/entity"
	"log"
	"sort"
)

//获取部门数据列表
func SelectDeptList(dept entity.Dept) []entity.Dept {
	deptList := make([]entity.Dept, 0)
	sql := DbEngine.Select("*")
	if dept.DeptName != "" {
		sql.Where("dept_name like ?", "%"+dept.DeptName+"%")
	}
	if dept.Status != "" {
		sql.Where("status = ?", dept.Status)
	}
	err := sql.Find(&deptList)
	if err != nil {
		log.Panicln("select dept list error ", err)
	}
	return deptList
}

//根据部门id查询部门详情
func SelectDeptByDeptId(deptId int64) entity.Dept {
	var dept entity.Dept
	_, err := DbEngine.Id(deptId).Get(&dept)
	if err != nil {
		fmt.Println("select dept by dept_id error", err)
	}
	return dept
}

//新增部门数据
func InsertSysDeptData(dept entity.Dept) error {
	//获取父元素数据
	d := SelectDeptByDeptId(dept.DeptId)
	dept.Ancestors = d.Ancestors + "," + string(d.DeptId)
	_, err := DbEngine.Insert(dept)
	return err
}

//修改
func UpdateSysDeptData(dept entity.Dept) error {
	_, err := DbEngine.Id(dept.DeptId).Update(dept)
	return err
}

//删除
func DeleteSysDeptByDeptId(deptId int64) error {
	_, err := DbEngine.Id(deptId).Delete(entity.Dept{})
	return err
}

//获取全部部门数据
func GetSysDeptDataList() []entity.Dept {
	dept := make([]entity.Dept, 0)
	err := DbEngine.Where("status = ?", 0).Find(&dept)
	if err != nil {
		log.Print("select dept list all error ", err)
	}
	return dept
}
func DeptBuildData(list []entity.Dept) map[int64]map[int64]entity.Dept {
	var data map[int64]map[int64]entity.Dept = make(map[int64]map[int64]entity.Dept)
	for _, v := range list {
		id := v.DeptId
		fid := v.ParentId
		if _, ok := data[fid]; !ok {
			data[fid] = make(map[int64]entity.Dept)
		}
		data[fid][id] = v
	}
	return data
}

func DeptMakeTreeCore(index int64, data map[int64]map[int64]entity.Dept) []entity.Dept {
	tmp := make([]entity.Dept, 0)
	for id, item := range data[index] {
		if data[id] != nil {
			item.Children = DeptMakeTreeCore(id, data)
		}
		tmp = append(tmp, item)
	}
	return tmp
}

//菜单排序
func DeptArraySort(dept []entity.Dept) {
	sort.Slice(dept, func(i, j int) bool {
		if dept[i].OrderNum < dept[j].OrderNum {
			return true
		}
		return false
	})
	for _, v := range dept {
		if v.Children != nil {
			DeptArraySort(v.Children)
		}
	}
}

//构建前端所需要的数据树
func BuildDeptTree(dept []entity.Dept) []entity.DeptVo {
	list := make([]entity.DeptVo, 0)
	for _, v := range dept {
		d := entity.DeptVo{
			Id:    v.DeptId,
			Label: v.DeptName,
		}
		if len(v.Children) > 0 && v.Children != nil {
			d.Children = BuildDeptTree(v.Children)
		}
		list = append(list, d)
	}
	return list
}
